<template>
	<view class="edit-home">
		<!-- 富文本工具 -->
		<view class="rich-text-tools">
			<view v-for="(item,index) in editorConfig" class="iconfont"
				:class="{[item.icon]: true,'active': item.isSelected}" @click="tEditToolEntryFn(item)">
				<text>{{item.label}}</text>
			</view>
		</view>

		<!-- 标题输入 -->
		<view class="title-in">
			<input v-model="articleContent.title" type="text" placeholder="输入标题"
				placeholder-class="title-placeholder" />
		</view>

		<!-- 富文本书写区域 -->
		<view class="rich-text-container">
			<editor id="editor" class="editor-container" placeholder="输入要发布的内容" show-img-resize show-img-size
				show-img-toolbar @ready="onEditorReady" @focus="onEditorFocus" @input="onEditorInput"
				@statuschange="onStatuschange">
			</editor>
		</view>

		<!-- 发布文章 -->
		<view class="submit">
			<u-button @click="submit" :disabled="!articleContent.title.length" type="success" text="发布"></u-button>
		</view>
		<!-- 颜色选择器 -->
		<t-color-picker ref="colorPicker" @confirm="colorConfirm"></t-color-picker>
	</view>
</template>

<script>
	const db = uniCloud.database()
	const articleCollect = db.collection('article')

	import {
		changeStatus
	} from "@/utils/speciallyToolsFn.js"
	import {
		getLocationByIp,
		getVarType,
		getImgSrc
	} from "@/utils/common.js"
	import tColorPicker from '@/components/t-color-picker/t-color-picker.vue'
	export default {
		onLoad(e) {
			if (Object.keys(e).length) {
				this.receivedArg = e
				this.mode = e.mode
				this.getDataById(e.article_id)
			}

			console.log(e, Object.keys(e));
		},
		data() {
			return {
				receivedArg: {},
				mode: 'add',
				currentToolIndex: -1,
				articleContent: {
					title: '',
					content: '',
					desc: '',
					thumb: [],
					city: '',
					province: '',
				},
				editorCtx: {},
				editorMap: {
					color(color) {
						const ctx = this.editorCtx.format('color', color)
					},
					bold(value = 'bold') {
						const ctx = this.editorCtx.format(value)
					},
					italic() {
						const ctx = this.editorCtx.format('italic')
					},
					underline() {
						const ctx = this.editorCtx.format('underline')
					},
					alignLeft() {
						const ctx = this.editorCtx.format('align', 'left')
					},
					alignCenter() {
						const ctx = this.editorCtx.format('align', 'center')
					},
					alignRight() {
						const ctx = this.editorCtx.format('align', 'right')
					},
					insertImage() {
						uni.chooseImage({
							success: async res => {

								uni.showLoading({
									title: "上传中请稍后",
									mask: true
								})
								for (let item of res.tempFiles) {
									let suffix = item.path.substring(item.path.lastIndexOf("."));
									let randomName = Date.now() + "" + String(Math.random()).substr(3, 6) +
										suffix
									try {
										let res = await uniCloud.uploadFile({
											filePath: item.path,
											cloudPath: item.name || randomName
										})
										this.editorCtx.insertImage({
											src: res.fileID
										})
										// this.articleContent.thumb.length < 3 ? this.articleContent.thumb.push(
										// 	res.fileID) : ''

									} catch (e) {
										console.log({
											'出错了': e.message
										});
										uni.showToast({
											title: e.message,
											icon: "error",
											duration: 2000
										});

									}


								}
								uni.hideLoading()
							}
						})
					},
					insertHref() {
						const ctx = this.editorCtx
					},
				},
				editorConfig: [{
						icon: "icon-zitiyanse",
						label: "字体颜色",
						type: "color",
						isSelected: false
					},
					{
						icon: "icon-zitijiacu",
						label: "字体加粗",
						type: "bold",
						isSelected: false
					},
					{
						icon: "icon-zitixieti",
						label: "字体倾斜",
						type: "italic",
						isSelected: false
					},
					{
						icon: "icon-zitixiahuaxian",
						label: "下划线",
						type: "underline",
						isSelected: false
					},
					{
						icon: "icon-zuoduiqi",
						label: "左对齐",
						type: "alignLeft",
						isSelected: false
					},
					{
						icon: "icon-juzhongduiqi",
						label: "居中对齐",
						type: "alignCenter",
						isSelected: false
					},
					{
						icon: "icon-youduiqi",
						label: "右对齐",
						type: "alignRight",
						isSelected: false
					},
					{
						icon: "icon-charutupian",
						label: "插入图片",
						type: "insertImage",
						isSelected: false
					},
					{
						icon: "icon-charulianjie",
						label: "插入链接",
						type: "insertHref",
						isSelected: false
					},
				],
			};
		},
		methods: {
			colorConfirm(e) {
				const color = e.hex
				this.editorMap.color.call(this, color)
			},
			setData(data) {
				this.articleContent.title = data.title
				this.editorCtx.setContents({
					html: data.content
				})
			},
			async getDataById(id) {
				try {
					let resultData = await articleCollect.doc(id)
						.field("title,content,thumb")
						.get({
							getOne: true
						})
					this.setData(resultData.result.data)
					console.log({
						resultData
					});

				} catch (e) {
					// this.skeletonEnabled = false
					uni.showToast({
						title: e.message.slice(0, 30),
						icon: "error"
					})
					console.log('edit 错误', e);
				}
			},
			async submit() {
				uni.showLoading({
					title: '发布中'
				})
				try {
					await this.getLocation()

					this.getEditorContent()

					if (this.mode == 'update') {
						let res = await articleCollect.doc(this.receivedArg.article_id).update({
							...this.articleContent
						})
						console.log({
							res
						});

					} else if (this.mode == 'add') {
						// 添加数据至数据库
						await articleCollect.add(this.articleContent)
					}

					this.otherOperation()

				} catch (e) {
					console.log('出错了', e);
					uni.hideLoading()
					uni.showToast({
						title: '发布失败',
						icon: "error"
					})

				}
			},
			clearData() {
				// 复位this.articleContent中的内容
				// this.articleContent中的value只有[]和 ""类型
				Object.keys(this.articleContent).forEach(key => {
					let value = this.articleContent[key]
					this.articleContent[key] = getVarType(value) == 'Array' ? [] : ''
				})

				// 清除富文本内容
				this.editorCtx.clear()
			},
			otherOperation() {
				uni.hideLoading()
				uni.showToast({
					title: '发布成功',
					icon: "success"
				})

				setTimeout(() => {
					uni.switchTab({
						url: "/pages/index/index"
					})
					this.clearData()
				}, 1000)
			},
			async getLocation() {
				try {
					let location = await getLocationByIp()
					location = location.data
					// console.log({
					// 	location
					// });

					if (location.status == 0) {
						uni.showToast({
							title: '获取发布位置失败',
							icon: "error"
						})
						return Promise.reject('获取发布位置失败')
					}
					// 保存位置信息
					this.articleContent.city = location.city.length ? location.city : '非法ip'
					this.articleContent.province = location.province.length ? location.province : '非法ip'
				} catch (e) {
					return Promise.reject(e.errMsg)
					// console.log('出错了', e.errMsg);
				}

			},
			getEditorContent() {
				console.log('获取富文本内容');
				this.editorCtx.getContents({
					success: (e) => {
						// console.log({
						// 	e
						// });
						const {
							html,
							text
						} = e
						this.articleContent.desc = text.slice(0, 50)
						this.articleContent.content = html
						this.articleContent.thumb = getImgSrc(html)

					},
				})
			},
			tEditToolEntryFn(item) {
				item.isSelected = !item.isSelected
				if (item.type == 'color') {
					this.$refs.colorPicker.open();
					return
				}
				this.editorMap[item.type].call(this)
			},
			onEditorInput() {},
			onEditorFocus() {},
			onStatuschange(e) {
				// console.log({
				// 	e
				// });
				// 实时更新复选框工具栏的是否选中状态
				changeStatus(e.detail, this.editorConfig)
			},
			onEditorReady(e) {
				// 初始化富文本

				// #ifdef MP-BAIDU
				this.editorCtx =
					requireDynamicLib("editorLib").createEditorContext("editor");
				// #endif

				// #ifdef APP-PLUS || H5 ||MP-WEIXIN
				uni
					.createSelectorQuery()
					.select("#editor")
					.context((res) => {
						this.editorCtx = res.context;
						// console.log(this.editorCtx);
					})
					.exec();
				// #endif
			},
		},
	};
</script>

<style lang="scss">
	.active {
		color: $theme-primary;
	}

	.edit-home {
		padding: $pd;
	}

	.rich-text-tools {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		column-gap: 20rpx;
		row-gap: 18rpx;
		justify-items: left;
		padding: $pd;
		background-color: $cl;
		border-radius: $br;

		.iconfont {
			// &::selection {
			// 	color: red;
			// }

			text {
				margin-left: 8rpx;
			}
		}
	}

	.title-in {
		margin-bottom: 30rpx;

		input {
			height: 120rpx;
			font-size: 40rpx;
			border-bottom: 1px solid $cl;
		}

		.title-placeholder {
			// color: $cl;
		}
	}

	.rich-text-container {
		border: 1px solid #eaeaea;
		margin-top: $mg;
		padding: $pd;
		height: calc(100vh - 622rpx);

		#editor {
			height: 100%;
			// background-color: #CCCCCC;
		}
	}
</style>